package com.ronghuanet.car.service.impl;

import com.ronghuanet.basic.util.PageList;
import com.ronghuanet.car.es.doc.CarDoc;
import com.ronghuanet.car.es.repository.CarDocRepository;
import com.ronghuanet.car.query.CarSearchQuery;
import com.ronghuanet.car.service.ICarSearchService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.joda.time.DateTimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class CarSearchServiceImpl implements ICarSearchService {

    @Autowired
    private CarDocRepository repository;

    //query boot must/filter
    //sort
    //from size
    @Override
    public PageList<CarDoc> search(CarSearchQuery query) {

        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //1高级查询
        //1.1 查询 keyword--->title,shopName,typeName,carIno
        String keyword = query.getKeyword();
        if (StringUtils.isNotBlank(keyword))
            boolQuery.must(QueryBuilders.multiMatchQuery(keyword.trim(),
                    "title","shopName","typeName","carInfo"));
        //1.2 过滤
        List<QueryBuilder> filters = boolQuery.filter();

        Integer costeffective = query.getCosteffective();
        Integer rushsale = query.getRushsale();
        Integer quasinewcar = query.getQuasinewcar();
        Integer transitivecountry = query.getTransitivecountry();
        Long carType = query.getCarType();
        if (costeffective!=null)
             filters.add(QueryBuilders.termQuery("costeffective",costeffective));
        if (rushsale!=null)
             filters.add(QueryBuilders.termQuery("rushsale",rushsale));
        if (quasinewcar!=null)
             filters.add(QueryBuilders.termQuery("quasinewcar",quasinewcar));
        if (transitivecountry!=null)
             filters.add(QueryBuilders.termQuery("transitivecountry",transitivecountry));
        if (carType!=null)
             filters.add(QueryBuilders.termQuery("typeId",carType));

        Integer carAgeType = query.getCarAgeType();
        Integer carAge = query.getCarAge();
        if (carAgeType!= null && carAge!=null){
            Date date = new Date(new Date().getTime() - carAge * 365 * 24 * 60 * 60 * 1000);
            if (carAgeType.intValue()==0) //以下 0---值
            {
                //reigstertime+五年时间>=当前时间
                //reigstertime>=当前时间-五年时间
                filters.add(QueryBuilders.rangeQuery("reigstertime").gte(date));
            }else{ //以上值-----无穷大
                //reigstertime+五年时间<=当前时间
                //reigstertime<=当前时间-五年时间
                filters.add(QueryBuilders.rangeQuery("reigstertime").lte(date));
            }
        }
        BigDecimal priceMin = query.getPriceMin();
        BigDecimal priceMax = query.getPriceMax();

        if (priceMin!=null)
            filters.add(QueryBuilders.rangeQuery("costprice").gte(priceMin));
        if (priceMax!=null)
            filters.add(QueryBuilders.rangeQuery("costprice").lte(priceMax));

        builder.withQuery(boolQuery);

        //2排序
        String orderType = query.getOrderType();
        String orderField = query.getOrderField();//jg cl lc no
        orderField = orderField==null?"jg":orderField; //默认价格排序

        //2.1 排序方式处理
        SortOrder sortOrder = SortOrder.DESC;
        if ("asc".equals(orderType))
            sortOrder = SortOrder.ASC;


        if ("jg".equals(orderField)){ //价格
            builder.withSort(SortBuilders.fieldSort("costprice").order(sortOrder));
        }
        if ("cl".equals(orderField)){//车龄
            builder.withSort(SortBuilders.fieldSort("reigstertime").order(sortOrder));
        }
        if ("lc".equals(orderField)){//里程
            builder.withSort(SortBuilders.fieldSort("mileage").order(sortOrder));
        }
        if ("no".equals(orderField)){//最新上架时间
            builder.withSort(SortBuilders.fieldSort("onsaletime").order(sortOrder));
        }


        //3分页
        builder.withPageable(PageRequest.of(query.getStart(),
                query.getPageSize()));

        //4封装数据
        Page<CarDoc> carDocs = repository.search(builder.build());

        List<CarDoc> rows = carDocs.getContent();
        long total = carDocs.getTotalElements();
        return new PageList<>(total,rows);
    }

}
